import os
import django
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from assets.models import (
    Organization, Department, Location, AssetCategory, Asset, 
    Supplier, Contract, Warehouse, Consumable
)

class Command(BaseCommand):
    help = '初始化系统权限和用户组'

    def handle(self, *args, **options):
        # 定义用户组和权限
        permission_groups = {
            '资产管理员': {
                'permissions': [
                    'add_asset', 'change_asset', 'delete_asset', 'view_asset',
                    'add_assetcategory', 'change_assetcategory', 'delete_assetcategory', 'view_assetcategory',
                ]
            },
            '组织管理员': {
                'permissions': [
                    'add_organization', 'change_organization', 'delete_organization', 'view_organization',
                    'add_department', 'change_department', 'delete_department', 'view_department',
                    'add_location', 'change_location', 'delete_location', 'view_location',
                ]
            },
            '供应商管理员': {
                'permissions': [
                    'add_supplier', 'change_supplier', 'delete_supplier', 'view_supplier',
                    'add_contract', 'change_contract', 'delete_contract', 'view_contract',
                ]
            },
            '库存管理员': {
                'permissions': [
                    'add_warehouse', 'change_warehouse', 'delete_warehouse', 'view_warehouse',
                    'add_consumable', 'change_consumable', 'delete_consumable', 'view_consumable',
                ]
            },
            '报表查看员': {
                'permissions': [
                    'view_asset', 'view_organization', 'view_department', 'view_location',
                    'view_supplier', 'view_contract', 'view_warehouse', 'view_consumable',
                ]
            }
        }

        # 创建用户组和分配权限
        for group_name, group_data in permission_groups.items():
            # 获取或创建用户组
            group, created = Group.objects.get_or_create(name=group_name)
            
            if created:
                self.stdout.write(f'创建用户组: {group_name}')
            else:
                self.stdout.write(f'用户组已存在: {group_name}')
                # 清空现有权限
                group.permissions.clear()
            
            # 分配权限
            for perm_codename in group_data['permissions']:
                try:
                    # 根据权限codename查找权限
                    if perm_codename.startswith('add_'):
                        content_type = ContentType.objects.get_for_model(self.get_model_by_name(perm_codename[4:]))
                    elif perm_codename.startswith('change_'):
                        content_type = ContentType.objects.get_for_model(self.get_model_by_name(perm_codename[7:]))
                    elif perm_codename.startswith('delete_'):
                        content_type = ContentType.objects.get_for_model(self.get_model_by_name(perm_codename[7:]))
                    elif perm_codename.startswith('view_'):
                        content_type = ContentType.objects.get_for_model(self.get_model_by_name(perm_codename[5:]))
                    else:
                        continue
                    
                    permission = Permission.objects.get(
                        content_type=content_type,
                        codename=perm_codename
                    )
                    group.permissions.add(permission)
                except Permission.DoesNotExist:
                    self.stdout.write(self.style.WARNING(f'权限不存在: {perm_codename}'))
                except ContentType.DoesNotExist:
                    self.stdout.write(self.style.WARNING(f'内容类型不存在: {perm_codename}'))
            
            self.stdout.write(f'为用户组 {group_name} 分配了 {group.permissions.count()} 个权限')

        self.stdout.write(
            self.style.SUCCESS('权限和用户组初始化完成')
        )

    def get_model_by_name(self, model_name):
        """
        根据模型名称获取模型类
        """
        model_mapping = {
            'organization': Organization,
            'department': Department,
            'location': Location,
            'assetcategory': AssetCategory,
            'asset': Asset,
            'supplier': Supplier,
            'contract': Contract,
            'warehouse': Warehouse,
            'consumable': Consumable,
        }
        return model_mapping.get(model_name.lower(), None)